//获取package.josn的window属性的内容
const op= require("./package.json"); //获取package.josn的window属性的内容
const winOp=op.window




// 错误处理函数
function handleError(error) {
  console.error("Window operation error:", error);
  // 尝试恢复窗口状态
  try {
    win.setAlwaysOnTop(true);
    win.show();
    const screenWidth = window.screen.availWidth;
    const x = Math.floor((screenWidth - winOp.width) / 2);
    win.moveTo(x, 0);
  } catch (e) {
    console.error("Recovery failed:", e);
  }
}

const init = function () {
  try {
    // 设置窗口属性
    win.setShowInTaskbar(false);
    win.setAlwaysOnTop(true);

    // 恢复保存的目录
    const savedFolders = JSON.parse(localStorage.getItem('savedFolders') || '[]');
    const container = document.getElementById("items-container");
    savedFolders.forEach(folder => {
      createFolderItem(folder.name, container, folder.path);
    });

    // 初始化窗口位置和大小
    const screenWidth = window.screen.availWidth;
    //获取窗口高度
    const x = Math.floor((screenWidth - winOp.width) / 2);
    win.moveTo(x, -winOp.height/2);
    window.win=win
    // 显示窗口
    win.show();

    // 设置窗口属性
    win.setResizable(true);
    // win.setMinimumSize(800, 60);

    // 监听窗口失去焦点事件，确保始终置顶
    win.on("blur", function () {
      win.setAlwaysOnTop(true);
    });

    // 添加自定义窗口拖动逻辑
    const toolbar = document.getElementById("toolbar");
    let isDragging = false;
    let startX, startY;
    let initialWindowX, initialWindowY;

    // 鼠标按下事件
    toolbar.addEventListener("mousedown", function (e) {
      isDragging = true;
      startX = e.screenX;
      startY = e.screenY;

      // 获取当前窗口位置
      initialWindowX = window.screenX;
      initialWindowY = window.screenY;

      toolbar.style.cursor = "grabbing";
      toolbar.classList.add("dragging");
    });

    // 鼠标移动事件
    document.addEventListener("mousemove", function (e) {
      if (!isDragging) return;
console.log("e.screenX:", e.screenX);
      // 计算鼠标移动的距离
      const deltaX = e.screenX - startX;
      const deltaY = e.screenY - startY;

      // 计算新窗口位置
      const newX = initialWindowX + deltaX;
      const newY = initialWindowY + deltaY;

      // 检测是否接近屏幕顶部（20像素内）
      const threshold = 20;
      if (newY < threshold) {
        // 吸附到顶部
        win.moveTo(newX, 0);
        
        // 添加吸附动画效果
        toolbar.style.transition = "transform 0.2s ease-out";
        toolbar.style.transform = "translateY(0)";
        
        // 重置拖动起点，避免跳跃
        startY = e.screenY;
        initialWindowY = 0;
      } else {
        // 正常移动
        win.moveTo(newX, newY);
        
        // 移除吸附动画效果
        toolbar.style.transition = "none";
        toolbar.style.transform = "none";
      }
    });

    // 鼠标释放事件
    document.addEventListener("mouseup", function () {
      if (isDragging) {
        isDragging = false;
        toolbar.style.cursor = "grab";
        toolbar.classList.remove("dragging");
        
        // 清除吸附动画效果
        toolbar.style.transition = "none";
        toolbar.style.transform = "none";
      }
    });

    // 防止拖动过程中选中文本
    toolbar.addEventListener("selectstart", function (e) {
      if (isDragging) {
        e.preventDefault();
      }
    });
    // 处理鼠标移入窗口的情况
    document.addEventListener("mouseenter",function(event){
     if( event.offsetY>5 ){
       smoothMoveToD(win,win.x,0)
      smoothResizeD(win,winOp.width,winOp.height)
     } 
    })
    // 处理鼠标离开窗口的情况
    document.addEventListener("mouseleave", function (event) {
      if (isDragging) {
        isDragging = false;
        toolbar.style.cursor = "grab";
        toolbar.classList.remove("dragging");
      }
       if( event.offsetY>5 ){ 
         smoothMoveToD(win,win.x,-winOp.height/2)
        smoothResizeD(win,winOp.height,winOp.height)
      }

    });

    // 确保在窗口失去焦点时重置拖动状态
    win.on("blur", function () {
      if (isDragging) {
        isDragging = false;
        toolbar.style.cursor = "grab";
        toolbar.classList.remove("dragging");
      }
      win.setAlwaysOnTop(true);
    });

    // 获取容器元素

    // 添加拖放事件监听器
    document.body.addEventListener("dragover", (e) => {
      e.preventDefault();
      e.stopPropagation();
    });

    document.body.addEventListener("drop", (e) => {
      e.preventDefault();
      e.stopPropagation();
      // 获取拖放的文件夹
      const items = e.dataTransfer.items;

      for (let i = 0; i < items.length; i++) {
        // 尝试获取File对象
        const file = items[i].getAsFile();
        if (file) {
          // 使用File.path获取绝对路径
          const path = file.path;
          const name = file.name;
          if (items[i].kind === 'file') {
            if (file.type === '') {
              // 可能是文件夹
              console.log("文件夹绝对路径:", path);
              // 检查是否已存在相同路径
              const savedFolders = JSON.parse(localStorage.getItem('savedFolders') || '[]');
              const exists = savedFolders.some(f => f.path === path);
              if (!exists) {
                createFolderItem(name, container, path);
              } else {
                alert('该文件夹已存在: ' + name);
              }
            } else {
              // 是文件
              console.log("文件绝对路径:", path);
            }
          }
        } else {
          // 回退到webkitGetAsEntry方式
          const entry = items[i].webkitGetAsEntry();
              if (entry) {
                if (entry.isDirectory) {
                  console.log("文件夹信息:", entry);
                  // 检查是否已存在相同路径
                  const savedFolders = JSON.parse(localStorage.getItem('savedFolders') || '[]');
                  const exists = savedFolders.some(f => f.path === entry.fullPath);
                  if (!exists) {
                    createFolderItem(entry.name, container, entry.fullPath);
                  } else {
                    alert('该文件夹已存在: ' + entry.name);
                  }
                } else {
                  console.log("文件名:", entry.name);
                }
              }
        }
      }
    });

    // 设置窗口最小尺寸
    // win.setMinimumSize(800, 60);

    // 监听窗口大小变化，确保高度正确
    win.on("resize", function (width, height) {
      if (height !== 60) {
        win.resizeTo(width, 60);
      }
    });

    // 设置窗口为可拖动
    win.setResizable(true);

    // 监听窗口焦点变化
    win.on("focus", function () {
      console.log("Window focused");
    });

    // 确保窗口始终可见
    setInterval(function () {
      try {
        win.setAlwaysOnTop(true);
      } catch (e) {
        handleError(e);
      }
    }, 5000);

    // 添加关闭按钮事件处理
    document
      .querySelector("#close-btn")
      .addEventListener("click", function () {
        console.log("Window closed");
        try {
          win.close();
        } catch (e) {
          handleError(e);
          // 如果正常关闭失败，尝试强制关闭
          nw.App.quit();
        }
      });
  } catch (error) {
    console.log(11111);
    handleError(error);
  }
};

// 创建文件夹项的函数
function createFolderItem(folderName, container, fullPath) {
  const itemDiv = document.createElement("div");
  itemDiv.className = "folder-item";

  const box = document.createElement("div");
  box.className = "folder-box";

  const name = document.createElement("div");
  name.className = "folder-name";
  name.textContent = folderName;

  // 使用传入的完整路径
  const folderPath = fullPath;
  itemDiv.dataset.path = folderPath;

  // 保存到localStorage
  const savedFolders = JSON.parse(localStorage.getItem('savedFolders') || '[]');
  if (!savedFolders.some(f => f.path === folderPath)) {
    savedFolders.push({
      name: folderName,
      path: folderPath
    });
    localStorage.setItem('savedFolders', JSON.stringify(savedFolders));
  }

  // 添加点击事件处理
  box.addEventListener("click", async function () {
    const process = require("child_process");
    // 添加点击动画效果
    box.classList.add("clicking");
    setTimeout(() => box.classList.remove("clicking"), 200);
    
    // 规范化路径（确保使用正斜杠）
    const normalizedPath = folderPath.replace(/\\/g, "/");

    // 使用code命令打开文件夹
    try {
      const child = process.spawn("code", [normalizedPath], {
        detached: true,
        stdio: "ignore",
        shell: true,
        windowsHide: true
      });
      
      child.on('error', (err) => {
        console.error('启动VSCode失败:', err);
        alert(`无法启动VSCode: ${err.message}\n请确保VSCode已安装并已将code命令添加到系统PATH中。`);
      });
      
      child.unref();
    } catch (error) {
      console.error("启动VSCode失败:", error);
      alert(`启动VSCode失败: ${error.message}\n请确保VSCode已安装并已将code命令添加到系统PATH中。`);
    }
  });

  itemDiv.appendChild(box);
  itemDiv.appendChild(name);
  container.appendChild(itemDiv);

  // 添加键盘支持
  box.setAttribute("tabindex", "0");
  box.setAttribute("role", "button");

  box.addEventListener("keydown", (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      box.click();
    }
  });

  // 添加键盘焦点样式
  box.addEventListener("focus", () => {
    box.style.outline = "2px solid #0078d4";
    box.style.outlineOffset = "2px";
  });

  box.addEventListener("blur", () => {
    box.style.outline = "";
    box.style.outlineOffset = "";
  });
}

// 添加滚轮事件处理
function setupWheelScrolling() {
  const container = document.getElementById("items-container");
  container.addEventListener("wheel", function(e) {
    // 阻止默认的垂直滚动行为
    e.preventDefault();
    // 将垂直滚动转换为水平滚动
    this.scrollLeft += e.deltaY;
  }, { passive: false });
}

// 窗口加载完成后执行
window.addEventListener("load", function() {
  init();
  setupWheelScrolling();
});